<template>
  <div class="create-blog-page">
    <!-- 导航栏 -->
    <header class="navbar">
      <div class="navbar-container">
        <button class="btn-back" @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </button>
        <h1 class="page-title">创建新文章</h1>
        <div class="navbar-actions">
          <button class="btn-draft" @click="saveDraft">
            <el-icon><DocumentCopy /></el-icon>
            保存草稿
          </button>
          <button class="btn-publish" @click="handleSubmit">
            <el-icon><Promotion /></el-icon>
            发布文章
          </button>
        </div>
      </div>
    </header>

    <!-- 主内容 -->
    <main class="main-wrapper">
      <div class="editor-container">
        <div class="editor-content">
          <!-- 标题输入 -->
          <div class="title-section">
            <input
              v-model="blogForm.title"
              type="text"
              placeholder="请输入文章标题..."
              class="title-input"
              maxlength="100"
            />
            <span class="char-count">{{ blogForm.title.length }}/100</span>
          </div>

          <!-- 分类选择 -->
          <div class="form-section">
            <label class="form-label">
              <el-icon><Collection /></el-icon>
              选择分类
            </label>
            <el-select
              v-model="blogForm.categoryId"
              placeholder="请选择文章分类"
              size="large"
              class="category-select"
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </div>

          <!-- 摘要输入 -->
          <div class="form-section">
            <label class="form-label">
              <el-icon><Document /></el-icon>
              文章摘要
            </label>
            <textarea
              v-model="blogForm.summary"
              placeholder="请输入文章摘要，简要描述文章内容..."
              class="summary-textarea"
              maxlength="200"
              rows="4"
            ></textarea>
            <span class="char-count">{{ blogForm.summary.length }}/200</span>
          </div>

          <!-- 标签输入 -->
          <div class="form-section">
            <label class="form-label">
              <el-icon><PriceTag /></el-icon>
              文章标签
            </label>
            <div class="tags-input-wrapper">
              <div class="tags-display">
                <span
                  v-for="(tag, index) in blogForm.tags"
                  :key="index"
                  class="tag-item"
                >
                  {{ tag }}
                  <el-icon class="tag-close" @click="removeTag(index)">
                    <Close />
                  </el-icon>
                </span>
                <input
                  v-model="currentTag"
                  type="text"
                  placeholder="输入标签后按回车添加"
                  class="tag-input"
                  @keydown.enter.prevent="addTag"
                  @keydown.space.prevent="addTag"
                />
              </div>
              <div class="tag-hint">按下回车或空格键添加标签</div>
            </div>
          </div>

          <!-- 内容编辑器 -->
          <div class="form-section">
            <label class="form-label">
              <el-icon><Edit /></el-icon>
              文章内容
            </label>
            <div class="editor-wrapper">
              <textarea
                v-model="blogForm.content"
                placeholder="开始写作，支持 Markdown 格式...&#10;&#10;示例：&#10;# 一级标题&#10;## 二级标题&#10;**粗体** *斜体*&#10;- 列表项&#10;&#10;```javascript&#10;// 代码块&#10;console.log('Hello World');&#10;```"
                class="content-editor"
              ></textarea>
              <div class="editor-toolbar">
                <div class="toolbar-left">
                  <span class="word-count">
                    字数：{{ getWordCount(blogForm.content) }}
                  </span>
                </div>
                <div class="toolbar-right">
                  <el-tooltip content="支持 Markdown 语法" placement="top">
                    <span class="markdown-badge">
                      <el-icon><Document /></el-icon>
                      Markdown
                    </span>
                  </el-tooltip>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧预览 -->
        <div class="preview-panel">
          <div class="preview-header">
            <h3>
              <el-icon><View /></el-icon>
              实时预览
            </h3>
          </div>
          <div class="preview-content">
            <h1 class="preview-title">{{ blogForm.title || '文章标题' }}</h1>
            <div v-if="blogForm.summary" class="preview-summary">
              {{ blogForm.summary }}
            </div>
            <div v-if="blogForm.tags.length > 0" class="preview-tags">
              <span v-for="tag in blogForm.tags" :key="tag" class="preview-tag">
                #{{ tag }}
              </span>
            </div>
            <div class="preview-body" v-html="formattedContent"></div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  DocumentCopy,
  Promotion,
  Collection,
  Document,
  PriceTag,
  Edit,
  View,
  Close
} from '@element-plus/icons-vue'
import { createBlog, getBlogCategories } from '../api/blog'
import { parseMarkdown, getWordCount } from '../utils/markdown'
import { tagsToString } from '../utils/tags'

const router = useRouter()

const blogForm = ref({
  title: '',
  categoryId: null,
  summary: '',
  content: '',
  tags: []
})

const categories = ref([])
const currentTag = ref('')

// 使用公共工具将 Markdown 转换为 HTML
const formattedContent = computed(() => {
  if (!blogForm.value.content) {
    return '<p class="empty-hint">内容将在这里显示...</p>'
  }
  return parseMarkdown(blogForm.value.content)
})

const fetchCategories = async () => {
  try {
    const res = await getBlogCategories()
    categories.value = res.data || res || []
  } catch (error) {
    console.error('获取分类列表失败:', error)
    categories.value = []
  }
}

const addTag = () => {
  const tag = currentTag.value.trim()
  if (tag && !blogForm.value.tags.includes(tag)) {
    if (blogForm.value.tags.length >= 5) {
      ElMessage.warning('最多只能添加5个标签')
      return
    }
    blogForm.value.tags.push(tag)
    currentTag.value = ''
  }
}

const removeTag = (index) => {
  blogForm.value.tags.splice(index, 1)
}

const saveDraft = () => {
  ElMessage.info('草稿保存功能开发中...')
}

const handleSubmit = async () => {
  // 验证
  if (!blogForm.value.title.trim()) {
    ElMessage.warning('请输入文章标题')
    return
  }
  if (!blogForm.value.categoryId) {
    ElMessage.warning('请选择文章分类')
    return
  }
  if (!blogForm.value.summary.trim()) {
    ElMessage.warning('请输入文章摘要')
    return
  }
  if (!blogForm.value.content.trim()) {
    ElMessage.warning('请输入文章内容')
    return
  }

  try {
    const submitData = {
      ...blogForm.value,
      tags: tagsToString(blogForm.value.tags)  // 使用公共工具转换标签
    }

    await createBlog(submitData)
    ElMessage.success('发布成功！')
    router.push('/my-blogs')
  } catch (error) {
    console.error('发布失败:', error)
  }
}

const goBack = () => {
  if (blogForm.value.title || blogForm.value.content) {
    if (confirm('确定要放弃编辑吗？未保存的内容将丢失。')) {
      router.back()
    }
  } else {
    router.back()
  }
}

onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.create-blog-page {
  min-height: 100vh;
  background: var(--bg-primary);
}

/* 导航栏 */
.navbar {
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-normal);
  position: sticky;
  top: 0;
  z-index: 1000;
  backdrop-filter: blur(20px);
  box-shadow: var(--shadow-sm);
}

.navbar-container {
  max-width: 1800px;
  margin: 0 auto;
  padding: 16px 32px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.btn-back {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border: 1.5px solid var(--border-normal);
  border-radius: 8px;
  background: var(--bg-tertiary);
  color: var(--text-secondary);
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-back:hover {
  border-color: var(--primary-start);
  color: var(--primary-start);
  background: var(--bg-hover);
}

.page-title {
  font-size: 18px;
  font-weight: 700;
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin: 0;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.navbar-actions {
  display: flex;
  gap: 12px;
}

.btn-draft,
.btn-publish {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-draft {
  background: var(--bg-tertiary);
  color: var(--text-secondary);
  border: 1.5px solid var(--border-normal);
}

.btn-draft:hover {
  border-color: var(--primary-start);
  color: var(--primary-start);
  background: var(--bg-hover);
}

.btn-publish {
  background: var(--gradient-primary);
  color: var(--bg-primary);
  box-shadow: var(--shadow-glow);
}

.btn-publish:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 212, 255, 0.5);
}

/* 主内容 */
.main-wrapper {
  max-width: 1800px;
  margin: 0 auto;
  padding: 32px;
}

.editor-container {
  display: grid;
  grid-template-columns: 1fr 500px;
  gap: 32px;
  align-items: start;
}

.editor-content {
  background: var(--bg-card);
  border-radius: 12px;
  padding: 36px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-light);
}

/* 标题输入 */
.title-section {
  position: relative;
  margin-bottom: 32px;
}

.title-input {
  width: 100%;
  font-size: 32px;
  font-weight: 800;
  color: var(--text-bright);
  border: none;
  outline: none;
  padding: 0;
  background: transparent;
  font-family: inherit;
}

.title-input::placeholder {
  color: var(--text-tertiary);
  opacity: 0.5;
}

.char-count {
  position: absolute;
  right: 0;
  bottom: -24px;
  font-size: 12px;
  color: var(--text-tertiary);
}

/* 表单区域 */
.form-section {
  margin-bottom: 32px;
  position: relative;
}

.form-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 12px;
}

.form-label .el-icon {
  color: var(--primary-start);
  font-size: 18px;
}

.category-select {
  width: 100%;
}

.category-select :deep(.el-input__wrapper) {
  border-radius: 8px;
  background: var(--bg-tertiary);
  box-shadow: 0 0 0 1px var(--border-normal) inset;
  padding: 8px 12px;
}

.category-select :deep(.el-input__wrapper:hover) {
  background: var(--bg-hover);
  box-shadow: 0 0 0 1px var(--primary-start) inset;
}

.category-select :deep(.el-input__wrapper.is-focus) {
  background: var(--bg-hover);
  box-shadow: 0 0 0 2px var(--primary-start) inset !important;
}

.category-select :deep(.el-input__inner) {
  color: var(--text-bright);
}

.summary-textarea {
  width: 100%;
  padding: 14px;
  border: 1.5px solid var(--border-normal);
  border-radius: 8px;
  font-size: 14px;
  color: var(--text-primary);
  background: var(--bg-tertiary);
  line-height: 1.7;
  resize: vertical;
  font-family: inherit;
  transition: all 0.2s;
}

.summary-textarea:hover {
  border-color: var(--primary-start);
  background: var(--bg-hover);
}

.summary-textarea:focus {
  outline: none;
  border-color: var(--primary-start);
  background: var(--bg-hover);
  box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.1);
}

.summary-textarea::placeholder {
  color: var(--text-tertiary);
}

/* 标签输入 */
.tags-input-wrapper {
  position: relative;
}

.tags-display {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 12px;
  border: 1.5px solid var(--border-normal);
  border-radius: 8px;
  background: var(--bg-tertiary);
  min-height: 48px;
  transition: all 0.2s;
}

.tags-display:hover,
.tags-display:focus-within {
  border-color: var(--primary-start);
  background: var(--bg-hover);
  box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.1);
}

.tag-item {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: var(--gradient-primary);
  color: var(--bg-primary);
  border-radius: 6px;
  font-size: 13px;
  font-weight: 600;
}

.tag-close {
  cursor: pointer;
  font-size: 14px;
  transition: transform 0.2s;
}

.tag-close:hover {
  transform: scale(1.2);
}

.tag-input {
  flex: 1;
  min-width: 200px;
  border: none;
  outline: none;
  font-size: 14px;
  color: var(--text-bright);
  background: transparent;
  padding: 6px 8px;
}

.tag-input::placeholder {
  color: var(--text-tertiary);
}

.tag-hint {
  font-size: 12px;
  color: var(--text-tertiary);
  margin-top: 8px;
}

/* 内容编辑器 */
.editor-wrapper {
  position: relative;
}

.content-editor {
  width: 100%;
  min-height: 500px;
  padding: 18px;
  border: 1.5px solid var(--border-normal);
  border-radius: 8px;
  font-size: 15px;
  color: var(--text-primary);
  background: var(--bg-tertiary);
  line-height: 1.8;
  resize: vertical;
  font-family: 'Monaco', 'Courier New', monospace;
  transition: all 0.2s;
}

.content-editor:hover {
  border-color: var(--primary-start);
  background: var(--bg-hover);
}

.content-editor:focus {
  outline: none;
  border-color: var(--primary-start);
  background: var(--bg-hover);
  box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.1);
}

.content-editor::placeholder {
  color: var(--text-tertiary);
  font-family: inherit;
}

.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid var(--border-normal);
}

.word-count {
  font-size: 12px;
  color: var(--text-tertiary);
  font-weight: 500;
}

.markdown-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  background: rgba(14, 165, 233, 0.15);
  color: var(--primary-start);
  border-radius: 6px;
  font-size: 12px;
  font-weight: 600;
}

/* 预览面板 */
.preview-panel {
  position: sticky;
  top: 88px;
  background: var(--bg-card);
  border-radius: 12px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-light);
  max-height: calc(100vh - 120px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.preview-header {
  padding: 18px 20px;
  border-bottom: 1px solid var(--border-normal);
  background: rgba(14, 165, 233, 0.05);
}

.preview-header h3 {
  font-size: 15px;
  font-weight: 700;
  color: var(--text-bright);
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.preview-header .el-icon {
  color: var(--primary-start);
  font-size: 18px;
}

.preview-content {
  padding: 32px;
  overflow-y: auto;
  flex: 1;
}

.preview-title {
  font-size: 26px;
  font-weight: 800;
  color: var(--text-bright);
  margin: 0 0 18px 0;
  line-height: 1.3;
}

.preview-summary {
  font-size: 14px;
  color: var(--text-secondary);
  line-height: 1.7;
  margin-bottom: 18px;
  padding: 14px;
  background: rgba(14, 165, 233, 0.08);
  border-left: 3px solid var(--primary-start);
  border-radius: 4px;
}

.preview-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.preview-tag {
  font-size: 12px;
  color: var(--primary-start);
  background: rgba(14, 165, 233, 0.15);
  padding: 4px 10px;
  border-radius: 4px;
  font-weight: 600;
}

.preview-body {
  font-size: 15px;
  line-height: 1.8;
  color: var(--text-primary);
}

.preview-body :deep(h1),
.preview-body :deep(h2),
.preview-body :deep(h3) {
  color: var(--text-bright);
  font-weight: 700;
  margin: 24px 0 12px 0;
}

.preview-body :deep(h1) { font-size: 24px; }
.preview-body :deep(h2) { font-size: 20px; }
.preview-body :deep(h3) { font-size: 18px; }

.preview-body :deep(p) {
  margin: 0 0 16px 0;
}

.preview-body :deep(ul) {
  margin: 16px 0;
  padding-left: 24px;
}

.preview-body :deep(li) {
  margin: 8px 0;
}

.preview-body :deep(pre) {
  background: var(--bg-secondary);
  color: var(--text-bright);
  padding: 16px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 16px 0;
  border: 1px solid var(--border-normal);
}

.preview-body :deep(code) {
  font-family: 'Monaco', 'Courier New', monospace;
  font-size: 14px;
}

.preview-body :deep(strong) {
  font-weight: 700;
  color: var(--text-bright);
}

.preview-body :deep(em) {
  font-style: italic;
  color: var(--text-secondary);
}

.preview-body :deep(table) {
  width: 100%;
  border-collapse: collapse;
  margin: 20px 0;
  background: var(--bg-tertiary);
  border-radius: 8px;
  overflow: hidden;
}

.preview-body :deep(th),
.preview-body :deep(td) {
  padding: 10px 12px;
  border: 1px solid var(--border-normal);
  text-align: left;
}

.preview-body :deep(th) {
  background: var(--bg-hover);
  color: var(--text-bright);
  font-weight: 600;
}

.preview-body :deep(td) {
  color: var(--text-primary);
}

.preview-body :deep(blockquote) {
  border-left: 3px solid var(--primary-start);
  padding-left: 1em;
  margin: 16px 0;
  color: var(--text-secondary);
  font-style: italic;
  background: rgba(0, 212, 255, 0.05);
  padding: 12px 16px;
  border-radius: 0 6px 6px 0;
}

.preview-body :deep(a) {
  color: var(--primary-start);
  text-decoration: none;
  border-bottom: 1px solid rgba(0, 212, 255, 0.3);
  transition: all 0.3s;
}

.preview-body :deep(a:hover) {
  border-bottom-color: var(--primary-start);
}

.empty-hint {
  color: var(--text-tertiary);
  font-style: italic;
}

/* 响应式 */
@media (max-width: 1400px) {
  .editor-container {
    grid-template-columns: 1fr;
  }

  .preview-panel {
    display: none;
  }
}

@media (max-width: 768px) {
  .navbar-container {
    padding: 12px 16px;
  }

  .page-title {
    position: static;
    transform: none;
    font-size: 16px;
  }

  .main-wrapper {
    padding: 16px;
  }

  .editor-content {
    padding: 24px 16px;
  }

  .title-input {
    font-size: 24px;
  }

  .navbar-actions {
    display: none;
  }
}
</style>
